package com.cskaoyan.service.wx.auth;

import com.cskaoyan.bean.*;
import com.cskaoyan.bean.vo.admin.auth.Md5Util;
import com.cskaoyan.bean.vo.wx.auth.AuthLoginVo;
import com.cskaoyan.bean.vo.wx.auth.UserInfoVo;
import com.cskaoyan.bean.vo.wx.auth.WxUserUtil;
import com.cskaoyan.mapper.MarketUserMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: bwj
 * @Date: 2022/09/09/14:06
 * @Description: 微信 登录，登出
 */
@Service
public class WxAuthServiceImpl implements WxAuthService {
    @Autowired
    MarketUserMapper userMapper;
    @Override
    public AuthLoginVo authLogin(String username, String password) {
        Subject subject = SecurityUtils.getSubject();
        //执行登录
        String pwd=null;
        try {
            pwd = Md5Util.getMd5(password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        String host="wx";
        UsernamePasswordToken token = new UsernamePasswordToken(username, pwd,host);
        //登录不成功会发生异常
        try {
            subject.login(token);
        } catch (AuthenticationException e) {
            return null;
        }
        //判断是否认证成功
        if (subject.isAuthenticated()) {
            //修改登录时间
            MarketUser user = new MarketUser();
            user.setLastLoginTime(new Date());
            MarketUserExample marketUserExample = new MarketUserExample();
            marketUserExample.createCriteria().andIdEqualTo(WxUserUtil.userUtil().getId());
            userMapper.updateByExampleSelective(user,marketUserExample);
        }
        //获取session信息
        Session session = subject.getSession();
        //获得principal信息
        //realm那边传入的第一个参数
        MarketUser principal = (MarketUser) subject.getPrincipals().getPrimaryPrincipal();
        UserInfoVo userInfoVo = new UserInfoVo();
        userInfoVo.setNickName(principal.getUsername());
        userInfoVo.setAvatarUrl(principal.getAvatar());
        AuthLoginVo authLoginVo = new AuthLoginVo();
        authLoginVo.setUserInfo(userInfoVo);
        authLoginVo.setToken((String) session.getId());
        return authLoginVo;
    }

    @Override
    public InfoData authInfo(String token) {
        return null;
    }
}
